package cn.chainco.cts.utils;

import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil{
	public static void addCookie(HttpServletResponse response, String cookieName, String cookieValue, String path, int cookieMaxAge){
		try{
			response.setHeader("P3P", "CP=CAO PSA OUR");
			Cookie c = new Cookie(cookieName, URLEncoder.encode(cookieValue, "utf-8"));
			c.setMaxAge(cookieMaxAge);
			c.setPath(path);
			response.addCookie(c);
		}catch(Exception ex){
		}
	}

	public static void addCookie(HttpServletResponse response, String cookieName, String cookieValue, String path, int cookieMaxAge, String domain){
		try{
			Cookie c = new Cookie(cookieName, cookieValue);
			c.setMaxAge(cookieMaxAge);
			c.setPath(path);
			c.setDomain(domain);
			response.addCookie(c);
		}catch(Exception ex){
		}
	}

	public static void addCookie(HttpServletResponse response, Cookie cookie){
		try{
			response.addCookie(cookie);
		}catch(Exception e){
		}
	}

	public static String getCookieValue(HttpServletRequest request, String cookieName){
		if("cts_locale".equals(cookieName)){
			return "zh_CH";
		}
		String cookieValue = "";
		try{
			Cookie c[] = request.getCookies();
			if(c != null){
				for(int n = 0; n < c.length; n++){
					if(c[n].getName().equals(cookieName)){
						cookieValue = URLDecoder.decode(c[n].getValue(), "utf-8");
					}
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return cookieValue;
	}
}
